package com.simple.car.loader.server.annotation.impl;

import android.content.Context;

import com.simple.car.loader.server.annotation.Init;
import com.simple.car.loader.server.manager.impl.BeamManager;
import com.simple.car.loader.server.manager.impl.ControllerManager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;

public class InitImpl {

    public static void init(Context context) {
        Collection<Object> values = BeamManager.getInstance().values();
        values.forEach(o -> initMethod(o, context));
        values = ControllerManager.getInstance().values();
        values.forEach(o -> initMethod(o, context));
    }

    private static void initMethod(Object o, Context context) {
        Method[] methods = o.getClass().getDeclaredMethods();
        for (Method method : methods) {
            Init init = method.getDeclaredAnnotation(Init.class);
            if (init == null) {
                continue;
            }
            int count = method.getParameterCount();
            boolean accessible = method.isAccessible();
            try {
                method.setAccessible(true);
                if (count == 0) {
                    method.invoke(o);
                } else if (count == 1) {
                    method.invoke(o, context);
                } else {
                    throw new IllegalArgumentException(String.format("非法的参数，初始化方法只支持无参或者一个参数，且参数类型只能是：%s", Context.class.getName()));
                }
                break;
            } catch (InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
                break;
            } finally {
                method.setAccessible(accessible);
            }
        }
    }
}
